package com.sunshine.listener;

import java.io.IOException;
import java.net.ServerSocket;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hsqldb.Server;

import com.sunshine.common.utils.LoggerUtils;
/**
 * HSQLDB数据库启动监听器
 * @author NGU-sunshine
 *
 */
public class StartHSQLDBListener implements ServletContextListener {

    private Server server;

    private final static String HSQLDB_PATH_PARAM_NAME = "HSQLDBPath";
    private final static String HSQLDB_NAME_PARAM_NAME = "HSQLDBName";
    private final static String HSQLDB_PORT_PARAM_NAME = "HSQLDBPort";

    private final static String DEFAULT_HSQLDB_PATH = "/WEB-INF/lib/hsqldb/";
    private final static String DEFAULT_HSQLDB_NAME = "fmmtest";
    private final static int DEFAULT_HSQLDB_PORT = 9001;
    
    //容器销毁方法
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        if (server != null) {
            server.shutdown();
        }
    }
    
    //容器初始化方法
    @Override
    public void contextInitialized(ServletContextEvent event) {
        String HSQLDBPath = event.getServletContext().getInitParameter(HSQLDB_PATH_PARAM_NAME);
        String HSQLDBName = event.getServletContext().getInitParameter(HSQLDB_NAME_PARAM_NAME);
        String paramPort = event.getServletContext().getInitParameter(HSQLDB_PORT_PARAM_NAME);
        if (HSQLDBPath == null || HSQLDBPath.length() == 0) {
            HSQLDBPath = DEFAULT_HSQLDB_PATH;
        }
        if (HSQLDBName == null || HSQLDBName.length() == 0) {
            HSQLDBName = DEFAULT_HSQLDB_NAME;
        }
        int HSQLDBPort = DEFAULT_HSQLDB_PORT;
        if (paramPort != null && paramPort.length() > 0) {
            HSQLDBPort = Integer.valueOf(paramPort);
        }
        String path = event.getServletContext().getRealPath(HSQLDBPath) + "/" + HSQLDBName;

        ServerSocket s = null;//因为有可能端口被占用,Server类内部会出异常,先在外部看下端口
        try {
            s = new ServerSocket(HSQLDBPort);
        } catch (IOException e) {
            LoggerUtils.info("HSQLDB was not started caused by " + e.getMessage());
            return;
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                   // LoggerUtils.info(e.getMessage());
                    return;
                }
            }
        }

        server = new Server();
        server.setDatabaseName(0, HSQLDBName);
        server.setDatabasePath(0, path);
        server.setPort(HSQLDBPort);
        server.setSilent(true);

        if (server == null) {
        }

        Thread thread = new Thread(new Runnable() {
            public void run() {
                server.start();
            }
        });
        thread.start();
    }

}